//
//  TodayViewController.m
//  TodayExtension
//
//  Created by keemanyeung on 14-9-21.
//  Copyright (c) 2014年 keemanyeung. All rights reserved.
//

#import "TodayViewController.h"
#import <NotificationCenter/NotificationCenter.h>


@interface TodayViewController () <NCWidgetProviding,NSURLConnectionDelegate>
{
    IBOutlet    UIButton  *_button;
    NSURLConnection *aSynConnection;
    NSMutableData *returnInfoData;
}

@end

@implementation TodayViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        NSLog(@"%s", __func__);
    }
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];

    [self setPreferredContentSize:CGSizeMake(self.view.frame.size.width, 30)];
    
    
   

    NSLog(@"%s", __func__);
}

-(void)getdate{
    NSString *urlString=@"http://www.weather.com.cn/data/sk/101010100.html";
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString: urlString]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval: 60];
    [request setHTTPShouldHandleCookies:FALSE];
    [request setHTTPMethod:@"GET"];
    // NSURLConnection* aSynConnection 可以申明为全局变量.
    // 在协议方法中，通过判断aSynConnection，来区分，是哪一个异步请求的返回数据。
    aSynConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
#pragma mark- NSURLConnectionDelegate 协议方法


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse{
    NSLog(@"请求成功！");
    returnInfoData=[[NSMutableData alloc]init];
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [returnInfoData appendData:data];
}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"didFailWithError");
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    if( [connection isEqual: aSynConnection])
    {
        NSString *asyReturn = [[NSString alloc] initWithData:returnInfoData encoding:NSUTF8StringEncoding];
        
        _button.hidden = YES;
    
        UIFont *tfont = [UIFont systemFontOfSize:14.0];
        NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:tfont,NSFontAttributeName,nil];
        CGSize sizeText = [asyReturn boundingRectWithSize:CGSizeMake(320, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
        //ios 6    CGSize sizeText1 = [str sizeWithFont:[UIFont systemFontOfSize:16.0f] constrainedToSize:CGSizeMake(320, 1000) lineBreakMode:NSLineBreakByCharWrapping];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, sizeText.height)];
        label.text = asyReturn;
        [label setFont:tfont];
        [label setLineBreakMode:NSLineBreakByCharWrapping];
        label.numberOfLines = 1000;
        [label setTextColor:[UIColor whiteColor]];
        [self.view addSubview:label];

        
        [self setPreferredContentSize:CGSizeMake(self.view.frame.size.width, sizeText.height)];
 
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"%s", __func__);
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    NSLog(@"%s", __func__);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//通常插件要消失的时候会调用，系统会在这个时候对插件截图，以便下次启动插件加载之前快速展示
- (void)widgetPerformUpdateWithCompletionHandler:(void (^)(NCUpdateResult))completionHandler {
    // Perform any setup necessary in order to update the view.
    
    // If an error is encoutered, use NCUpdateResultFailed
    // If there's no update required, use NCUpdateResultNoData
    // If there's an update, use NCUpdateResultNewData
    NSLog(@"%s", __func__);
    completionHandler(NCUpdateResultNewData);
}

//通过openURL的方式启动Containing APP
- (void)openURLContainingAPP
{
    [self.extensionContext openURL:[NSURL URLWithString:@"appextension://123"]
                 completionHandler:^(BOOL success) {
                     NSLog(@"open url result:%d",success);
                 }];
}

//执行完任务后调用该方法，系统会将插件杀掉
- (void)completeTask
{
    [self.extensionContext completeRequestReturningItems:nil completionHandler:^(BOOL expired) {
        NSLog(@"is expired:%d",expired);
    }];
}

//将自己从Today区域中移除，要想再次显示必须在contaning app中调用显示方法
- (void)removeSelf
{
    [[NCWidgetController widgetController] setHasContent:NO forWidgetWithBundleIdentifier:@"com.wangzz.app.extension"];
}




- (IBAction)selector:(UIButton *)sender
{
    [self getdate];
//    [self openURLContainingAPP];
    //在此调用上述方法进行测试
    
}


- (void)dealloc
{
    NSLog(@"%s", __func__);
}


@end
